{#
Copyright 2021 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
#}

<script>
{% include 'constants.js' %}

{% include 'l1timer.js' %}

function sort(arr) {
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length-1; j++) {
      if (arr[j] > arr[j+1]) {
        const tmp = arr[j];
        arr[j] = arr[j+1];
        arr[j+1] = tmp;
      }
    }
  }
  return arr;
}

function indexOfMin(arr) {
  let minValue = arr[0];
  let minIndex = 0;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] < minValue) {
      minValue = arr[i];
      minIndex = i;
    }
  }
  return minIndex;
}

function randomCacheLine() {
  return Math.floor(CACHE_LINES_PER_PAGE*Math.random());
}

const alignedMemory = new Uint8Array(new WebAssembly.Memory({
  initial: 1,
  maximum: 1,
}).buffer);
alignedMemory[8] = 1;

const accessArgs = new Uint32Array([0]);
function accessPage(trash) {
  const pageOffset = accessArgs[0]|0;
  return alignedMemory[pageOffset+trash];
}

const benchmark = new L1Timer(accessPage);

// accessPage will touch more cache lines besides the one that we trigger
// To find a cache line that is not used, we first iterate through all and
// choose the fastest one.
const cacheSetTimings = new Array(CACHE_LINES_PER_PAGE);
for (let set = 0; set < CACHE_LINES_PER_PAGE; set++) {
  cacheSetTimings[set] = benchmark.timeCacheSet(set);
}
const fastSet = indexOfMin(cacheSetTimings);

const testReps = {{ test_reps }};
const hits = new Array(testReps);
const misses = new Array(testReps);
const hitOffset = fastSet*CACHE_LINE_SZ;
const missOffset = (hitOffset + PAGE_SZ/2) % PAGE_SZ;
for (let i = 0; i < testReps; i++) {
  accessArgs[0] = hitOffset;
  hits[i] = benchmark.timeCacheSet(fastSet);
  accessArgs[0] = missOffset
  misses[i] = benchmark.timeCacheSet(fastSet);
}
window.top.postMessage({hits, misses}, "*");

</script>
